/**
 * @(#)JzprController.java 2017年9月2日
 * 
 * Copyright 2000-2017 by ChinanetCenter Corporation.
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ChinanetCenter Corporation ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with ChinanetCenter.
 * 
 */

package com.teamall.web.sjtj.controller;

import java.io.File;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.teamall.core.common.JModelAndView;
import com.teamall.core.common.Page;
import com.teamall.core.excel.ExcelUtils;
import com.teamall.framework.exception.BaseAppException;
import com.teamall.framework.log.LogManager;
import com.teamall.framework.util.DateUtils;
import com.teamall.framework.util.Utils;
import com.teamall.web.base.db.po.TownInfoPO;
import com.teamall.web.base.service.ITownInfoService;
import com.teamall.web.main.db.po.CodeStatTownPO;
import com.teamall.web.main.service.ICodeStatTownService;
import com.teamall.web.sjtj.db.po.CodeVisitedAidRankPO;
import com.teamall.web.sjtj.db.po.CodeVisitedTeamRankPO;
import com.teamall.web.sjtj.db.po.CodeVisitedTownRankPO;
import com.teamall.web.sjtj.service.ICodeVisitedAidRankService;
import com.teamall.web.sjtj.service.ICodeVisitedTeamRankService;
import com.teamall.web.sjtj.service.ICodeVisitedTownRankService;
import com.teamall.web.sjtj.vo.VisitedTownRankVO;
import com.teamall.web.xtgl.controller.BasicDataController;

/**
 * 精准派人
 * 
 * @author pan.xiaobo
 * @date 2017年9月2日
 * @version $Revision$
 */
@Controller
@RequestMapping("/jzpr")
public class JzprController {
    private static final LogManager logger = LogManager
            .getLogger(JzprController.class);

    @Autowired
    private ITownInfoService townInfoService;

    @Autowired
    private ICodeVisitedAidRankService codeVisitedAidRankService;

    @Autowired
    private ICodeVisitedTeamRankService codeVisitedTeamRankService;

    @Autowired
    private ICodeStatTownService codeStatTownService;

    @Autowired
    private ICodeVisitedTownRankService codeVisitedTownRankService;

    /**
     * 帮扶责任人走访排名-界面
     * 
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("/aidStaffRankIndex")
    public ModelAndView aidStaffRankIndex() throws BaseAppException {
        ModelAndView modelAndView = new JModelAndView(
                "/sjtj/jzpr_aidstaffRank_main");
        List<TownInfoPO> townInfoPOList = townInfoService
                .selectByArg(new TownInfoPO());

        modelAndView.addObject("townInfoPOList", townInfoPOList);
        modelAndView.addObject("currentYear", DateUtils.date2String(new Date(),
                DateUtils.STR_DATE_FORMAT_YEAR));
        return modelAndView;
    }

    /**
     * 帮扶责任人走访排名
     * 
     * @param codeVisitedAidRankPO
     * @param qryPage
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("/qryAidStaffRankData")
    @ResponseBody
    public Page<CodeVisitedAidRankPO> qryAidStaffRankData(
            CodeVisitedAidRankPO codeVisitedAidRankPO,
            Page<CodeVisitedAidRankPO> qryPage) throws BaseAppException {
        if (Utils.notEmpty(codeVisitedAidRankPO.getTownId())
                && -1 == codeVisitedAidRankPO.getTownId()) {
            codeVisitedAidRankPO.setTownId(null);
        }
        if (Utils.notEmpty(codeVisitedAidRankPO.getVillageId())
                && -1 == codeVisitedAidRankPO.getVillageId()) {
            codeVisitedAidRankPO.setVillageId(null);
        }

        codeVisitedAidRankService.selectByArgAndPage(codeVisitedAidRankPO,
                qryPage);
        int sortNum = (qryPage.getPage() - 1) * qryPage.getRows() + 1;
        for (CodeVisitedAidRankPO vPO : qryPage.getResultList()) {
            vPO.setSortNum(sortNum);
            sortNum++;
        }

        return qryPage;
    }

    /**
     * 帮扶责任人走访排名导出
     * 
     * @param response
     * @param codeVisitedAidRankPO
     * @throws Exception
     */
    @RequestMapping("exportAidStaffRankData")
    public void exportAidStaffRankData(HttpServletResponse response,
            CodeVisitedAidRankPO codeVisitedAidRankPO) throws Exception {
        logger.debug(codeVisitedAidRankPO.toString());
        if (Utils.notEmpty(codeVisitedAidRankPO.getTownId())
                && -1 == codeVisitedAidRankPO.getTownId()) {
            codeVisitedAidRankPO.setTownId(null);
        }
        if (Utils.notEmpty(codeVisitedAidRankPO.getVillageId())
                && -1 == codeVisitedAidRankPO.getVillageId()) {
            codeVisitedAidRankPO.setVillageId(null);
        }

        List<CodeVisitedAidRankPO> resultList = codeVisitedAidRankService
                .selectByArg(codeVisitedAidRankPO);
        if (null == resultList || resultList.size() == 0) {

        }
        int sortNum = 1;
        for (CodeVisitedAidRankPO one : resultList) {
            one.setSortNum(sortNum++);
        }

        // 数据中的key
        String keys[] = {
                "sortNum", "townName", "villageName", "staffName",
                "department", "visitedCountSum"
        };

        Workbook wb = null;
        OutputStream ouputStream = null;
        try {

            String tplPath = BasicDataController.class.getClassLoader()
                    .getResource("").getPath()
                    + "tpl_aidStaffRank.xls";
            logger.info(""
                    + BasicDataController.class.getClassLoader()
                            .getResource("").getPath());
            logger.info("excel模板路径：" + tplPath);
            wb = ExcelUtils.createWorkBookByTpl(new File(tplPath), 1, 0,
                    resultList, keys, keys);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader(
                    "Content-Disposition",
                    "attachment;filename="
                            + new String(("帮扶责任人走访排名_"
                                    + DateUtils.getCurrentDate() + ".xls")
                                    .getBytes(), "iso-8859-1"));
            ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            // ouputStream.close();
        }
        catch (Exception e) {
            logger.error("导出Excel时发生异常：" + e.getMessage(), e);
        }
        finally {
            try {
                if (ouputStream != null)
                    ouputStream.close();
            }
            catch (Exception e) {
                logger.error("导出Excel关闭流抛异常：", e);
            }
        }
    }

    /**
     * 工作队走访排名-界面
     * 
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("/teamRankIndex")
    public ModelAndView teamRankIndex() throws BaseAppException {
        ModelAndView modelAndView = new JModelAndView(
                "/sjtj/jzpr_teamRank_main");
        List<TownInfoPO> townInfoPOList = townInfoService
                .selectByArg(new TownInfoPO());

        modelAndView.addObject("townInfoPOList", townInfoPOList);
        modelAndView.addObject("currentYear", DateUtils.date2String(new Date(),
                DateUtils.STR_DATE_FORMAT_YEAR));
        return modelAndView;
    }

    /**
     * 工作队走访排名
     * 
     * @param codeVisitedAidRankPO
     * @param qryPage
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("/qryTeamRankData")
    @ResponseBody
    public Page<CodeVisitedTeamRankPO> qryTeamRankData(
            CodeVisitedTeamRankPO codeVisitedAidRankPO,
            Page<CodeVisitedTeamRankPO> qryPage) throws BaseAppException {
        if (Utils.notEmpty(codeVisitedAidRankPO.getTownId())
                && -1 == codeVisitedAidRankPO.getTownId()) {
            codeVisitedAidRankPO.setTownId(null);
        }
        if (Utils.notEmpty(codeVisitedAidRankPO.getVillageId())
                && -1 == codeVisitedAidRankPO.getVillageId()) {
            codeVisitedAidRankPO.setVillageId(null);
        }

        codeVisitedTeamRankService.selectByArgAndPage(codeVisitedAidRankPO,
                qryPage);
        int sortNum = (qryPage.getPage() - 1) * qryPage.getRows() + 1;
        for (CodeVisitedTeamRankPO vPO : qryPage.getResultList()) {
            vPO.setSortNum(sortNum);
            sortNum++;
        }

        return qryPage;
    }

    /**
     * 工作队走访排名导出
     * 
     * @param response
     * @param codeVisitedAidRankPO
     * @throws Exception
     */
    @RequestMapping("exportTeamRankData")
    public void exportTeamRankData(HttpServletResponse response,
            CodeVisitedTeamRankPO codeVisitedTeamRankPO) throws Exception {
        logger.debug(codeVisitedTeamRankPO.toString());
        if (Utils.notEmpty(codeVisitedTeamRankPO.getTownId())
                && -1 == codeVisitedTeamRankPO.getTownId()) {
            codeVisitedTeamRankPO.setTownId(null);
        }
        if (Utils.notEmpty(codeVisitedTeamRankPO.getVillageId())
                && -1 == codeVisitedTeamRankPO.getVillageId()) {
            codeVisitedTeamRankPO.setVillageId(null);
        }

        List<CodeVisitedTeamRankPO> resultList = codeVisitedTeamRankService
                .selectByArg(codeVisitedTeamRankPO);
        if (null == resultList || resultList.size() == 0) {

        }
        int sortNum = 1;
        for (CodeVisitedTeamRankPO one : resultList) {
            one.setSortNum(sortNum++);
        }

        // 数据中的key
        String keys[] = {
                "sortNum", "townName", "villageName", "visitedCountSum"
        };

        Workbook wb = null;
        OutputStream ouputStream = null;
        try {

            String tplPath = BasicDataController.class.getClassLoader()
                    .getResource("").getPath()
                    + "tpl_teamRank.xls";
            logger.info(""
                    + BasicDataController.class.getClassLoader()
                            .getResource("").getPath());
            logger.info("excel模板路径：" + tplPath);
            wb = ExcelUtils.createWorkBookByTpl(new File(tplPath), 1, 0,
                    resultList, keys, keys);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader(
                    "Content-Disposition",
                    "attachment;filename="
                            + new String(("工作队走访排名_"
                                    + DateUtils.getCurrentDate() + ".xls")
                                    .getBytes(), "iso-8859-1"));
            ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            // ouputStream.close();
        }
        catch (Exception e) {
            logger.error("导出Excel时发生异常：" + e.getMessage(), e);
        }
        finally {
            try {
                if (ouputStream != null)
                    ouputStream.close();
            }
            catch (Exception e) {
                logger.error("导出Excel关闭流抛异常：", e);
            }
        }
    }

    /**
     * 乡镇走访排名-界面
     * 
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("/townRankIndex")
    public ModelAndView townRankIndex() throws BaseAppException {
        ModelAndView modelAndView = new JModelAndView(
                "/sjtj/jzpr_townRank_main");
        List<TownInfoPO> townInfoPOList = townInfoService
                .selectByArg(new TownInfoPO());

        modelAndView.addObject("townInfoPOList", townInfoPOList);
        modelAndView.addObject("currentYear", DateUtils.date2String(new Date(),
                DateUtils.STR_DATE_FORMAT_YEAR));
        return modelAndView;
    }

    /**
     * 乡镇走访排名
     * 
     * @param codeVisitedAidRankPO
     * @param qryPage
     * @return
     * @throws BaseAppException
     */
    @RequestMapping("/qryTownRankData")
    @ResponseBody
    public Page<VisitedTownRankVO> qryTownRankData(
            VisitedTownRankVO visitedTownRankVO, Page<VisitedTownRankVO> qryPage)
            throws BaseAppException {
        if (Utils.notEmpty(visitedTownRankVO.getTownId())
                && -1 == visitedTownRankVO.getTownId()) {
            visitedTownRankVO.setTownId(null);
        }

        CodeStatTownPO qryStatTownPO = new CodeStatTownPO();
        qryStatTownPO.setTownId(visitedTownRankVO.getTownId());
        List<CodeStatTownPO> statTownList = codeStatTownService
                .selectByArg(qryStatTownPO);

        CodeVisitedTownRankPO qryVisitedTownRankPO = new CodeVisitedTownRankPO();
        qryVisitedTownRankPO.setTownId(visitedTownRankVO.getTownId());
        qryVisitedTownRankPO.setVtime(visitedTownRankVO.getVtime());
        List<CodeVisitedTownRankPO> townRankList = codeVisitedTownRankService
                .selectByArg(qryVisitedTownRankPO);

        if (null == statTownList || statTownList.size() == 0) {
            return qryPage;
        }
        List<VisitedTownRankVO> resultList = new ArrayList<VisitedTownRankVO>();
        for (CodeStatTownPO statTownPO : statTownList) {
            VisitedTownRankVO oneRow = new VisitedTownRankVO();
            BeanUtils.copyProperties(statTownPO, oneRow);
            int yearCount = 0;
            if (null != townRankList && townRankList.size() > 0) {
                for (CodeVisitedTownRankPO visitedTownRankPO : townRankList) {
                    if (statTownPO.getTownId() == visitedTownRankPO.getTownId()) {
                        if ("01".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setOneVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("02".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setTwoVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("03".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setThreeVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("04".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setFourVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("05".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setFiveVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("06".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setSixVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("07".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setSevenVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("08".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setEightVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("09".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setNineVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("10".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setTenVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("11".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setElevenVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        if ("12".equals(visitedTownRankPO.getVmonth())) {
                            oneRow.setTwelveVisitNum(visitedTownRankPO
                                    .getVisitedCountSum().intValue());
                        }
                        yearCount += visitedTownRankPO.getVisitedCountSum()
                                .intValue();
                    }
                }
            }

            oneRow.setYearVisitNum(yearCount);
            if (oneRow.getPovertyFamilyNum() > 0) {
                BigDecimal bd = new BigDecimal(1.0 * oneRow.getYearVisitNum()
                        / oneRow.getPovertyFamilyNum());
                bd = bd.setScale(2, 4);

                oneRow.setAvgVisitNum(bd.floatValue());
            }
            resultList.add(oneRow);
        }
        qryPage.setResultList(resultList);
        return qryPage;
    }

    /**
     * 乡镇走访排名导出
     * 
     * @param response
     * @param visitedTownRankVO
     * @throws Exception
     */
    @RequestMapping("exportTownRankData")
    public void exportTownRankData(HttpServletResponse response,
            VisitedTownRankVO visitedTownRankVO) throws Exception {
        Page<VisitedTownRankVO> resultPage = new Page<VisitedTownRankVO>();
        qryTownRankData(visitedTownRankVO, resultPage);
        // 数据中的key
        String keys[] = {
                "townName", "aidStaffNum", "povertyFamilyNum", "avgVisitNum",
                "yearVisitNum", "oneVisitNum", "twoVisitNum", "threeVisitNum",
                "fourVisitNum", "fiveVisitNum", "sixVisitNum", "sevenVisitNum",
                "eightVisitNum", "nineVisitNum", "tenVisitNum",
                "elevenVisitNum", "twelveVisitNum"
        };

        Workbook wb = null;
        OutputStream ouputStream = null;
        try {

            String tplPath = BasicDataController.class.getClassLoader()
                    .getResource("").getPath()
                    + "tpl_townRank.xls";
            logger.info(""
                    + BasicDataController.class.getClassLoader()
                            .getResource("").getPath());
            logger.info("excel模板路径：" + tplPath);
            wb = ExcelUtils.createWorkBookByTpl(new File(tplPath), 1, 0,
                    resultPage.getResultList(), keys, keys);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader(
                    "Content-Disposition",
                    "attachment;filename="
                            + new String(("乡镇走访排名_"
                                    + DateUtils.getCurrentDate() + ".xls")
                                    .getBytes(), "iso-8859-1"));
            ouputStream = response.getOutputStream();
            wb.write(ouputStream);
            ouputStream.flush();
            // ouputStream.close();
        }
        catch (Exception e) {
            logger.error("导出Excel时发生异常：" + e.getMessage(), e);
        }
        finally {
            try {
                if (ouputStream != null)
                    ouputStream.close();
            }
            catch (Exception e) {
                logger.error("导出Excel关闭流抛异常：", e);
            }
        }
    }
}
